/*******************************************************************************
 * Copyright (c) 2008 Sylvain Sicard.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Sylvain Sicard - initial API and implementation
 ******************************************************************************/
/*
 * Created on Feb 21, 2006
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package fr.jade.service.fm.reactor;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.objectweb.fractal.api.Component;
import org.objectweb.fractal.api.NoSuchInterfaceException;

import fr.jade.base.JadeBaseComponent;
import fr.jade.service.fm.deployment.DeploymentTask;
import fr.jade.service.fm.deployment.NewComponentTask;
import fr.jade.service.fm.deployment.StartTask;
import fr.jade.service.fm.deployment.StopTask;
import fr.jade.util.FractalUtil;
import fr.jade.util.JadeException;

public class LifeCyclePolicy extends JadeBaseComponent implements Policy{

  public int getPriorityLevel(){
    return 4;
  }

  public Set<DeploymentTask> execute(Map<Component, NewComponentTask> context, Set<Component> failedCmps_M, Set<Component> impactedCmps_M, Component newNode_M) throws JadeException {
    Set<DeploymentTask> tasks= new HashSet<DeploymentTask>();
    for(Component cmp_M : impactedCmps_M){
      checkAndCreateTask(context, tasks, cmp_M, false);
      checkAndCreateTask(context, tasks, cmp_M, true);
    }  
		for (Component cmp_M : failedCmps_M) {
			checkAndCreateTask(context, tasks, cmp_M, true);
		}
		return tasks;
	}
	
  protected void checkAndCreateTask(Map<Component, NewComponentTask> context, Set<DeploymentTask> tasks, Component cmp_M, boolean startTask){
    try{
      FractalUtil.getOptLifeCycleController(cmp_M);
      DeploymentTask t = null;
      if(startTask){
        t = new StartTask(context.get(cmp_M));
      }else{
        t = new StopTask(context.get(cmp_M));
      }
      tasks.add(t);
    }catch(NoSuchInterfaceException ignored){
      // no task to create
    }
  }
	
	
}
